<template>
  <div class="site-reservation">
    <!-- 景点选择栏 -->
    <div class="scenic-spots-selector">
      <h3>选择预约景点</h3>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载景点信息...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <p>{{ error }}</p>
        <button class="retry-button" @click="fetchScenicSpots">重试</button>
      </div>

      <!-- 景点列表 -->
      <div v-else class="spots-grid">
        <div
          v-for="spot in scenicSpots"
          :key="spot.id"
          class="spot-card"
          :class="{ active: selectedSpot?.id === spot.id }"
          @click="selectSpot(spot)"
        >
          <img
            :src="spot.image"
            :alt="spot.name"
            class="spot-image"
            @error="handleImageError($event)"
          />
          <div class="spot-info">
            <h4>{{ spot.name }}</h4>
            <p class="spot-price">¥{{ spot.basePrice }}起</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约详情 -->
    <SiteReservationDetail
      v-if="selectedSpot"
      :spot="selectedSpot"
      :ticket-count="ticketCount"
      @update-ticket-count="updateTicketCount"
      @date-selected="onDateSelected"
      @tourist-info-updated="onTouristInfoUpdated"
      @proceed-to-payment="proceedToPayment"
    />
  </div>
</template>

<script setup>
import { ref, reactive, inject, onMounted } from "vue";
import { useRouter } from "vue-router";
import SiteReservationDetail from "./SiteReservationDetail.vue";
import { getScenicSpotDetails } from "../../api/scenicSpots.js";

const router = useRouter();
const user = inject("user");

const scenicSpots = ref([]);
const selectedSpot = ref(null);
const selectedDate = ref(null);
const ticketCount = ref(1);
const touristInfo = reactive({
  contact: {},
  guests: [],
});
const isLoading = ref(false);
const error = ref("");

// 获取景点数据
const fetchScenicSpots = async () => {
  isLoading.value = true;
  error.value = "";

  try {
    const apiData = await getScenicSpotDetails();

    // 转换API返回的数据格式，映射到组件需要的字段
    scenicSpots.value = apiData.map((item) => ({
      id: item.id,
      name: item.name,
      // 修复图片路径拼接，处理coverImage可能以/开头的情况
      image:
        "http://192.168.199.231:9000/fznostalgia/scenicspot/" +
        (item.coverImage.startsWith("/")
          ? item.coverImage.substring(1)
          : item.coverImage),
      basePrice: item.basePrice,
      description: item.description,
      // 将bookingNotice字符串按换行符分割成数组
      notices: item.bookingNotice ? item.bookingNotice.split("\n") : [],
      refundPolicy: item.refundPolicy,
      // 将usageGuide作为usageInstructions使用
      usageInstructions: item.usageGuide,
    }));
    console.log("1111111111111111111111111", scenicSpots.value);
  } catch (err) {
    error.value = "加载景点信息失败，请稍后重试";
    console.error("获取景点数据失败:", err);
  } finally {
    isLoading.value = false;
  }
};

const selectSpot = (spot) => {
  // 检查用户是否登录
  if (!user.value.isLoggedIn) {
    if (confirm("您需要登录才能预约景点，是否立即登录？")) {
      router.push("/login");
    }
    return;
  }

  selectedSpot.value = spot;
  selectedDate.value = null;
  ticketCount.value = 1;
};

// 组件挂载时获取景点数据
onMounted(() => {
  fetchScenicSpots();
});

// 处理图片加载失败
const handleImageError = (event) => {
  // 使用项目内的默认图片路径或简单的文本提示
  event.target.alt = "图片加载失败";
  // 由于public/images目录不存在，我们使用纯CSS方式处理图片加载失败
  event.target.style.display = "none";
  const parent = event.target.parentNode;
  const placeholder = document.createElement("div");
  placeholder.className = "image-placeholder";
  placeholder.textContent = "图片加载失败";
  parent.appendChild(placeholder);
};

const updateTicketCount = (count) => {
  ticketCount.value = count;
};

const onDateSelected = (date) => {
  selectedDate.value = date;
};

const onTouristInfoUpdated = (info) => {
  Object.assign(touristInfo, info);
};

const proceedToPayment = () => {
  // 跳转到支付页面的逻辑
  console.log("跳转到支付页面", {
    spot: selectedSpot.value,
    date: selectedDate.value,
    ticketCount: ticketCount.value,
    touristInfo: touristInfo,
  });
  // 这里可以使用 router.push() 跳转到支付页面
};
</script>

<style scoped>
.site-reservation {
  width: 85%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.scenic-spots-selector {
  margin-bottom: 30px;
}

.scenic-spots-selector h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.spots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.spot-card {
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.spot-card:hover {
  border-color: var(--secondary-color);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.spot-card.active {
  border-color: var(--secondary-color);
  background: #f8fff8;
}

.spot-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: block;
}

/* 图片加载失败时的样式 */
.spot-image[src]:not([src=""]) {
  background: none;
}

.spot-image[src=""],
.spot-image:not([src]) {
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
  text-align: center;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid var(--secondary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #e74c3c;
}

.retry-button {
  margin-top: 15px;
  padding: 8px 20px;
  background-color: var(--secondary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.retry-button:hover {
  background-color: #2980b9;
}

.spot-info h4 {
  font-size: 18px;
  color: #333;
  margin: 0 0 5px 0;
}

.spot-price {
  font-size: 16px;
  color: var(--primary-color);
  font-weight: bold;
  margin: 0;
}

/* 图片加载失败的占位符样式 */
.image-placeholder {
  width: 100%;
  height: 150px;
  background: #f0f0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
  border: 1px dashed #ddd;
}
</style>
